/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package folders2;

import DlinkedList.DNode;
import DlinkedList.MyDList;
import java.io.*;
import sorting_searching.SData;
/**
 *
 * @author Administrator
 */


public class UserFileOperation2 implements UserFileOperation2Interface
{
    /*
    *Doubly linked list that contains all users in server
    * i.e. objects of UserFile2
    */
    private MyDList users;

    /**
     * Constructor to initialize new empty list of users
     * @throws java.io.IOException
     */
    public UserFileOperation2()throws IOException
    {
        users = new MyDList();
    }

    /**
     * This method is used to get users list
     * @return doubly linked list of users
     */
    public MyDList getUsers()
    {
        return users;
    }
    /**
     * This method is used to set users list
     * @param users
     */
    public void setUsers(MyDList users)
    {
        this.users = users;
    }
    /**
     * This method is used to read users file (in our case i use it to read file at the start of prject )
     * and loaded users informations in users list(loaded objects of users)
     * @throws java.io.IOException
     */
    public void readUsersFile()throws IOException
    {
        BufferedReader in = new BufferedReader(new FileReader("users.txt"));
        String line = "";
        String[]s;
        while((line = in.readLine()) != null)
        {
            
            if(! line.equals(""))
            {
                s = line.split(",");
                UsersFile2 f = new UsersFile2(s[0],s[1],Integer.parseInt(s[2]));
                users.add(f);
            }
        }
        in.close();
    }
    /**
     * This method is used to write users informations in users file
     * @throws java.io.IOException
     */
    public void writeUsersFile()throws IOException
    {
        BufferedWriter out = new BufferedWriter(new FileWriter("users.txt"));
        DNode u = users.getHeader();
        UsersFile2 v;
        int i = 0;
        while(u.getNext()!= users.getTrialer() && i < users.size())
        {
            u = u.getNext();
            v = (UsersFile2)u.getData();
            String line = v.getUserName()+","+v.getPassword()+","+v.getMessageCount();
            out.write(line+"\n");
            i++;
        }
        out.close();
    }
    /**
     * This method is used to increment number of sent messages to any user in the server
     * when user sent message to any other user
     * @param userId userName which message will sent to him
     */
    public void incrementMessageCounter(String userId)
    {
        String userName = userId.substring(0, userId.indexOf('@') );
        String mailserverName = userId.substring(userId.indexOf('@')+1).toLowerCase();
        String ourServer = "gomail".toLowerCase();
        if(!users.isEmpty() && mailserverName.contains(ourServer))
        {
            DNode u = users.getHeader();
            UsersFile2 v;
            boolean found = false;
            while(u.getNext() != users.getTrialer() && !found)
            {
                u = u.getNext();
                v = (UsersFile2)u.getData();
                if(v.getUserName().equalsIgnoreCase(userName))
                {
                    found = true;
                    v.setMessageCount(v.getMessageCount()+1);
                    u.setData(v);
                }
                else
                {
                    found = false;
                }
            }
        }
    }
    /**
     * This method is used to decrement number of sent messages to any user in the server to 0
     * because when he open mail he will receive all sent messages to him
     * @param userId userName
     */
    public void decrementMessageCounter(String userId)
    {
        if(!users.isEmpty())
        {
            DNode u = users.getHeader();
            UsersFile2 v;
            boolean found = false;
            while(u.getNext() != users.getTrialer() && !found)
            {
                u = u.getNext();
                v = (UsersFile2)u.getData();
                if(v.getUserName().equalsIgnoreCase(userId))
                {
                    found = true;
                    v.setMessageCount(0);
                    u.setData(v);
                }
                else
                {
                    found = false;
                }
            }
        }
    }
    /**
     * This method is used to delete user from server(i.e. from users list and users file)
     * @param userName userName
     */
    public void deleteUser(String userName)
    {
        SData list = new SData();
        list.copyList(users, userName);
        list.setCompareKey(2);          //compare between nodes
        list.sortList();
        DNode u = (DNode)list.binSearch();
        DNode v = u.getNext();
        DNode w = u.getPrev();
        v.setNext(w);
        w.setPrev(v);
        u.setNext(null);
        u.setPrev(null);
        u = null;
    }
    /**
     * This method is used to add new user to server
     * @param userFile new userName
     */
    public void addNewUser(UsersFile2 userFile)
    {
        users.add(userFile);
    }
    /**
     *  This method is used to checks if this username exist on server or not
     * @param name user name
     * @param password user password
     * @return result of type integer
     * returns -1 if user doesn't have mail in server
     * else returns number of messages sent to this user
     */
    public int mailExist(String name,String password)
    {
        SData search = new SData();
        UsersFile2 u = new UsersFile2(name,password);
        search.copyList(users, u);
        search.setCompareKey(1);
        search.sortList();
        Object find = search.binSearch();
        if(find == null)
        {
            return -1;
        }
        else
        {
            /*System.out.println("found");*/
            Object c = find;
            DNode v = (DNode) c;
            UsersFile2 w = (UsersFile2)v.getData();
            return w.getMessageCount();
        }
    }
}
